/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/* 
 * Copyright (c) 2009 City University of Hong Kong
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License m_version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * Author: Wilson Thong (wilsonwk@ee.cityu.edu.hk) 
 */
#include "packet-traversed-hop-calculator.h"
#include "ns3/log.h"
#include "ns3/packet.h"
#include "ns3/trace-source-accessor.h"
#include "ns3/pointer.h"
#include "ns3/uinteger.h"
#include "ns3/names.h"
#include "ns3/config.h"
#include "ns3/simulator.h"
#include <sstream>

NS_LOG_COMPONENT_DEFINE ("PacketTraversedHopCalculator");

namespace ns3 {
namespace eecityu {

using namespace std;

NS_OBJECT_ENSURE_REGISTERED (PacketTraversedHopCalculator);

PacketTraversedHopCalculator::PacketTraversedHopCalculator (void)
{
}

TypeId 
PacketTraversedHopCalculator::GetTypeId (void)
{
  static TypeId tid = TypeId ("ns3::PacketTraversedHopCalculator")
    .SetParent<Object> ()
    .AddAttribute ("SourceApplication", 
                   "A reference to a source appliction from where packets's TTL "
                   "value are monitored for calculating traversed hops",
                   PointerValue (),
                   MakePointerAccessor (&PacketTraversedHopCalculator::GetSourceApplication,
                                        &PacketTraversedHopCalculator::SetSourceApplication),
                   MakePointerChecker<Application> ())
    .AddTraceSource ("TransistHopRx", 
                     "Get the hops traversed of each received packet",
                     MakeTraceSourceAccessor (&PacketTraversedHopCalculator::m_getTraversedHopTrace))  
                     ;
  return tid;
}

Ptr<Application> 
PacketTraversedHopCalculator::GetSourceApplication () const
{
  NS_ASSERT_MSG (m_sourceApplication, 
    "GetSourceApplication () failed as the source application is not yet set!");
  return m_sourceApplication;
}

void 
PacketTraversedHopCalculator::SetSourceApplication (Ptr<Application> app)
{
  NS_ASSERT_MSG (m_sourceApplication == 0, 
    "GetSourceApplication () failed as the source application is set already!");
  m_sourceApplication = app;
  ostringstream sourceAppName;
  sourceAppName << "App" << &m_sourceApplication;
  NS_LOG_LOGIC ("Source application name is " << sourceAppName.str ());
  Names::Add (sourceAppName.str (), m_sourceApplication);
  Simulator::ScheduleNow (&Config::Set, "/Names/" + sourceAppName.str () + "/Socket/IpTtl", UintegerValue (g_defaultTtl));
  //Config::Set ("/Names/" + sourceAppName.str () + "/Socket/IpTtl", UintegerValue (g_defaultTtl));
  NS_LOG_LOGIC ("The Names/" << sourceAppName.str () 
    << "/Socket/IpTtl attribute is scheduled at now for setting it to " << (uint32_t) g_defaultTtl);
}

void 
PacketTraversedHopCalculator::PrepareTx (Ptr<const Packet> packet)
{
  NS_LOG_FUNCTION (packet);
  
  NS_ASSERT_MSG (m_sourceApplication, "Unable to proceed as the source application is not set!");
  // register the packet into this object so as to allow the RecordRx () of this object
  // to work on the packet
  NS_ASSERT_MSG (m_registeredPacket.insert (packet->GetUid ()).second, 
    "Cannot prepare traversed hops calculation on the same packet twice!");
  NS_LOG_LOGIC ("Registered the packet-" << packet->GetUid () << " to " << this);
}

void 
PacketTraversedHopCalculator::RecordRx (Ptr<Packet> packet, Ipv4Header const& ipHeader)
{
  NS_LOG_FUNCTION (packet);
  NS_ASSERT_MSG (m_sourceApplication, "Unable to proceed as the source application is not set!");

  // the number of hops traversed by the packet. 0 means n/a
  uint32_t traversedHop = 0;
  set<uint32_t>::size_type numRegPkts = m_registeredPacket.erase (packet->GetUid ());
  if (numRegPkts == 1)
  {
    NS_LOG_LOGIC ("Confirmed packet-" << packet->GetUid () << " is registered with " << this);
    // obtain the ttl value after the packet is traversed the network
    NS_LOG_LOGIC ("Ipv4Header = " << ipHeader);
    uint8_t ttl = ipHeader.GetTtl ();
    NS_LOG_LOGIC ("Packet ttl value = " << (uint32_t) ttl);
    // calculate the resulting number of hops traversed
    traversedHop = g_defaultTtl - ttl;
    m_getTraversedHopTrace (traversedHop);
    NS_LOG_INFO ("Packet-" << packet->GetUid () << " " << traversedHop << " hops");
  }
  else if (numRegPkts == 0)
    NS_LOG_LOGIC ("The packet is not registered to this PacketTraversedHopCalculator");
  else
    NS_ASSERT_MSG (false, "Unexpected error! The same packet is registered more than once to this PacketTraversedHopCalculator!");

  return;
}


DefaultTtlTag::DefaultTtlTag ()
{}

void 
PacketTraversedHopCalculator::DoDispose (void)
{
  NS_LOG_FUNCTION_NOARGS ();

  m_registeredPacket.clear ();
  // This is only a reference to the source application and thus
  // cannot be disposed here
  m_sourceApplication = 0;

  Object::DoDispose ();
}

TypeId 
DefaultTtlTag::GetTypeId (void)
{
  static TypeId tid = TypeId ("ns3::eecityu::DefaultTtlTag")
    .SetParent<Tag> ()
    .AddConstructor<DefaultTtlTag> ()
    ;
  return tid;
}

TypeId 
DefaultTtlTag::GetInstanceTypeId (void) const
{
  return GetTypeId ();
}

void 
DefaultTtlTag::SetTtl (uint8_t ttl)
{
  m_ttl = ttl;
}

uint8_t 
DefaultTtlTag::GetTtl (void) const
{
  return m_ttl;
}

uint32_t 
DefaultTtlTag::GetSerializedSize (void) const
{ 
  return 1;
}
void 
DefaultTtlTag::Serialize (TagBuffer i) const
{ 
  i.WriteU8 (m_ttl);
}
void 
DefaultTtlTag::Deserialize (TagBuffer i)
{ 
  m_ttl = i.ReadU8 ();
}
void
DefaultTtlTag::Print (std::ostream &os) const
{
  os << "Ttl=" << (uint32_t) m_ttl;
}


} // namespace eecityu
} // namespace ns3
